import { Button, Card, Input, Space, Table, Tree, Spin, Upload, Dropdown, Popconfirm, Modal, App } from 'antd';
import { useState, useEffect, useRef } from 'react'
import dynamicColumnJzzyApi from '../../../../../utils/apis/dynamicColumanJzzyApi';
import Api from '../../../../../utils/api';
import JzzyApi from '../../../../../utils/apis/JzzyApi';
import _ from 'lodash'
import { UpCircleOutlined } from '@ant-design/icons';
import ScrollTable from '../../../../common/ScrollTable';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import { Histogram } from '@antv/g2plot';
import PubSub from 'pubsub-js';
import FetchHelper from '../../../../../utils/helper/fetch-helper';
import { set } from 'ol/transform';
import cztxl from './cztxl';
import DetailModal from './DetailModal';
import EditModal from './EditModal';
import CztApi from '../../../../../utils/apis/CztApi';
import AutoGeom from '../../../../common/AutoGeom';
export default function NewCzt(props) {
    const [category, setCategory] = useState();
    const [jzzyData, setJzzyData] = useState();
    const [total, setTotal] = useState();
    const [loading, setLoading] = useState();
    const rootRef = useRef();
    const [node, setNode] = useState();
    const [open_daoChu, seOpen_daoChu] = useState(false);
    const [currentRecord, setCurrentRecord] = useState();
    const [detailOpen, setDetailOpen] = useState();

    const [editOpen, setEditOpen] = useState();

    const [autoGeomVisible, setAutoGeomVisible] = useState();

    const [params, setParams] = useState({
        pageSize: 10,
        pageNum: 1
    });

    const { modal, message } = App.useApp();

    useEffect(() => {
        Api.getCztCategroy().then(datas => {
            setCategory(datas.map(data => {
                data?.children?.forEach(item => {
                    item.cztzl = data.title
                })
                return {
                    ...data,
                    disabled: true
                }
            }))
            setNode(datas?.[0]?.children?.[0]);
            setParams(p => {
                return {
                    ...p,
                    cztxl: datas?.[0]?.children?.[0]?.title
                }
            })
        })
    }, [])

    useEffect(() => {
        //console.log("@-2",{...params})
        if (params?.cztxl) {
            setLoading(true);
            CztApi.list(params).then(resp => {
                setJzzyData(resp.rows)
                console.log(resp.rows);
                setTotal(resp.total);
            }).finally(e => {
                setLoading(false)
            })
        }
    }, [params])

    let cztxlDefs;
    if (params.cztxl) {
        cztxlDefs = cztxl?.[params.cztxl]
    }
    const actionCols = cztxlDefs ? [{
        title: '',
        render: (t, record) => {
            return <>
                <Button type="link" size='small' onClick={e => {
                    setCurrentRecord(record);
                    setDetailOpen(true)
                }}>查看</Button>
                <Button type="link" size='small' onClick={e => {
                    setCurrentRecord(record);
                    setEditOpen(true)
                }}>编辑</Button>
                <Button type="link" danger size='small' onClick={e => {
                    modal.confirm({
                        title: "提示",
                        content: "确定删除该条数据？",
                        onOk: async () => {
                            const resp = await FetchHelper.deleteJson(`/admin-api/ybyj/cztjcb/` + record.id);
                            if (resp.code === 200) {
                                message.success('删除成功');
                            } else {
                                message.error('删除失败,' + resp.msg);
                            }
                            setParams(p => {
                                return {
                                    ...p,
                                    pageNum: 1
                                }
                            })
                        }
                    })

                }}>删除</Button>
            </>
        }
    }] : []

    return <div className='layout-h h100'>
        <Card size='small' className='h100' style={{
            width: 240,
            marginRight: 12,
            overflow: "auto"
        }} title={"调查对象分类"}>
            {category && <Tree className='categray-tree' selectedKeys={[params.cztxl || params.jzzyMiddle]}
                treeData={category} blockNode
                defaultExpandAll
                // rootStyle={{ color: '#aaa' }}
                onSelect={(selectedKeys, { node }) => {
                    setNode(node)
                    seOpen_daoChu(true)
                    setParams(params => {
                        return {
                            pageSize: params.pageSize,
                            pageNum: 1,
                            cztxl: node.key
                        }
                    })


                }}
                fieldNames={{
                    title: 'title',
                    key: 'title'
                }}

            />}
        </Card>
        <Card size='small' className='h100 fill w0' style={{
            position: "relative"
        }} bodyStyle={{
            display: 'flex',
            flexDirection: "column",
            height: "100%"
        }}>
            <div style={{
                marginBottom: 12,
                display: 'flex',
                alignItems: "center",
                justifyContent: "space-between"
            }}>
                <Space>
                    <Button disabled={!cztxlDefs} type='primary' onClick={e => {
                        setCurrentRecord(null);
                        setEditOpen(true)
                    }}>新增</Button>
                    <Upload {...{
                        name: 'file',
                        action: '/admin-api/ybyj/cztjcb/import',
                        headers: {
                            authorization: 'authorization-text',
                        },
                        beforeUpload(file) {
                            const isValidFormat = file.type === 'application/vnd.ms-excel';


                            if (!isValidFormat) {
                                message.error('只能上传 .xls格式的文件!');
                            }


                            return isValidFormat
                        },
                        onChange(info) {
                            console.log('node', info)
                            if (info.file.status === 'done') {
                                message.success(`${info.file.name} 文件上传成功`);
                            } else if (info.file.status === 'error') {
                                message.error(`${info.file.name} 文件上传失败！\n数据表格可能与本数据表不一致，最好先导出一份数据，使用其模板写入数据后在进行上传`);
                                alert(`上传失败！\n状态码：${info.file?.response?.code}。\n错误信息：${info.file?.response?.msg}。`)
                            }
                        },
                    }}>
                        <Button disabled={!cztxlDefs} icon={<UpCircleOutlined />}>数据导入</Button>
                    </Upload>
                    <Button onClick={e => {
                        setAutoGeomVisible(true);
                    }}>自动上图</Button>
                    {/* <Button disabled={!cztxlDefs} key="download" onClick={() => {
                        
                        fetch(`/admin-api/ybyj/cztjcb/exportLike?columnNames=${'cztxl'}&key=${params.cztxl}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json;charset=UTF-8'
                            }
                        }).then(response => response.blob()).then(blob => {
                            const a = document.createElement("a");
                            a.download = "data.xls";
                            a.href = URL.createObjectURL(blob);
                            a.click();
                        }).catch(error => console.log(error))
                    }}>数据导出</Button> */}
                </Space>
                <div>
                    <Input.Search placeholder='输入名称查找'
                        allowClear
                        enterButton="查询"
                        onSearch={(value) => {
                            console.log("@-1", { ...params }, value)
                            setParams(params => {
                                return {
                                    ...params,
                                    cztmc: value,
                                    //jgmc:value,
                                    pageNum: 1
                                }
                            })
                        }}
                    />
                </div>
            </div>
            <div ref={rootRef} className="fill h0">
                {<ScrollTable style={{
                    // border:"1px solid #ddd"
                }}
                    loading={loading}
                    parentNode={rootRef.current}
                    size='small'
                    bordered
                    dataSource={jzzyData}
                    columns={[{
                        title: '承灾体名称',
                        dataIndex: 'cztmc',
                        // render: (t, record) => {
                        //     return record.cztmc || record.jgmc
                        // }
                    },

                    {
                        title: '地址',
                        dataIndex: 'jgxxdz',
                        render: (t, record) => {
                            return record.jgxxdz || record.xzqhmc
                        }
                    },
                    ...(cztxlDefs?.columns || []),
                    ...actionCols
                    ]}
                    pagination={{
                        current: params.pageNum,
                        pageSize: params.pageSize,
                        total,
                    }}
                    onChange={({ current }) => {
                        setParams(params => {
                            return {
                                ...params,
                                pageNum: current
                            }
                        })
                    }}
                />}
            </div>
        </Card>
        <DetailModal cztxlDefs={cztxlDefs} record={currentRecord} open={detailOpen} onCancel={e => {
            setDetailOpen(false);
        }} />
        {editOpen && <EditModal cztxlDefs={cztxlDefs} record={currentRecord} open={editOpen} onCancel={e => {
            setEditOpen(false);
        }} node={node} onOk={e => {
            setEditOpen(false);
            setCurrentRecord(null);
            setParams(p => {
                return {
                    ...p,
                    pageNum: 1
                }
            })
        }} />}
        {autoGeomVisible && <AutoGeom visible={autoGeomVisible} onCancel={e => setAutoGeomVisible(false)}
            params={{ cztxl: params?.cztxl }} listApi={CztApi.list} />}
    </div>;
}